import axios from 'axios'
import { store } from '@redux/store'
import { logout } from '@redux/reducers/basic'
import { Toast } from 'antd-mobile'
import { root } from './config'
import { getUrlPre } from '@js/tool'
// import { setList } from '@src/redux/reducers/pages'
// import { history } from '@router/history'
// import uuid from 'uuid'

export const instance = axios.create({
  headers: {
    'Content-Type': 'application/json',
    'Cache-Control': 'no-cache'
  },
  timeout: 1000 * 120
})

const globalStatus = {
  faile: false
}

instance.interceptors.request.use(function (config) {
  // config.url = `/api${config.url}`;
  return config
})


/**
 * 请求方法
 * @param {*} type 请求类型
 */
function request (type, isAuth, hasCode = false) {
  return async function (url, data = {}, config = {}) {
    const { basic } = store.getState()
    const { token, userInfo } = basic
    const option = {
      url: `${root}/${getUrlPre()}${url}`,
      method: type,
      headers: {},
      ...config
    }
    if (isAuth) {
      option.headers = {
        ...option.headers,
        Authorization: `Bearer ${token}`
      }
      if (data instanceof FormData) {
        data.append('uid', userInfo.id)
        if (hasCode) {
          data.append('tenant_code', userInfo.tenant_code)
        }
      } else {
        data.uid = userInfo.id
        if (hasCode) {
          data.tenant_code = userInfo.tenant_code
        }
      }
    }
    if (type === 'get' || type === 'delete') {
      option.params = data
    } else {
      option.data = data
    }
    return await new Promise((resolve, reject) => {
      instance(option).then((res) => {
        const d = res.data
        if (d.status !== 1) {
          Toast.show({ content: d.message })
          reject(new Error(d.message))
        } else {
          resolve(d)
        }
      }).catch((e) => {
        const { basic } = store.getState()
        if (e.response === undefined) {
          return false
        }
        const { status, data } = e.response
        if (isAuth && basic.token === '') {
          if (globalStatus.faile) {
            return undefined
          }
          Toast.show({ content: '未登录' })
          setTimeout(() => {
            location.href = `${location.origin}${root}/gate/login`
            // history.replace('/login')
            // store.dispatch(setList([{ element: 'login', title: '登录', id: uuid() }]))
          }, 1000)
          return reject(e)
        }
        if (status === 401 || (status === 500 && data.message === '登录超时')) {
          globalStatus.faile = true
          Toast.show({ content: token !== '' ? '登录超时' : '请先登录', afterClose: () => {
            store.dispatch(logout())
            location.href = `${location.origin}${root}/gate/login`
            // history.replace('/login')
            // store.dispatch(setList([{ element: 'login', title: '登录', id: uuid() }]))
          } })
        } else if (status === 504) {
          Toast.show({ content: '网络异常' })
        } else if (typeof data.message === 'string') {
          Toast.show({ content: data.message })
        } else if (status >= 400 && status < 500) {
          Toast.show({ content: '系统网络异常，请联系网络管理员' })
        } else {
          Toast.show({ content: '服务器异常，请联系管理员' })
        }
        reject(e)
      })
    })
  }
}

// 需要鉴权的请求
export const $get = request('get', true)
export const $delete = request('delete', true)
export const $post = request('post', true)
export const $put = request('put', true)

// 需要鉴权且带租户id的请求
export const $get_ = request('get', true, true)
export const $delete_ = request('delete', true, true)
export const $post_ = request('post', true, true)
export const $put_ = request('put', true, true)

// 不需要鉴权的请求
export const $freeGet = request('get', false)
export const $freeDelete = request('delete', false)
export const $freePost = request('post', false)
export const $freePut = request('put', false)

// 上传单个文件请求
export const requestOneFile = async function (file, progressFn = () => {}) {
  const config = {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: (progressEvent) => {
      // progressEvent.loaded  ==> 已上传的大小
      //  progressEvent.total ==>  文件大小
      // 进度条的数字
      progressFn(progressEvent.loaded)
    }
  }
  const formData = new FormData()
  formData.append('upload_file', file)
  const res = await $post('/api/common/upload', formData, config)
  if (res.status !== 1) {
    throw new Error(`文件上传失败：${res.message}`)
  }
  return res.data
}

// 上传多个文件请求
export const requestFiles = async function (files, setProgress = () => {}) {
  let total = 0
  const uploaded = []
  const unUpload = []
  const arr = []
  files.forEach(li => {
    if (li.id) {
      uploaded.push(li)
    } else {
      total += li.size
      unUpload.push(li)
      arr.push({
        name: li.name,
        size: li.size,
        loaded: 0
      })
    }
  })
  function compute () {
    let finish = 0
    arr.forEach(li => {
      finish += li.loaded
    })
    return Math.floor(finish / total * 100)
  }
  const list = unUpload.map((li, i) => {
    return requestOneFile(li, (p) => {
      arr[i].loaded = p
      setProgress(compute())
    })
  })
  return await Promise.all([...uploaded.map(li => Promise.resolve(li)), ...list])
}
